<?php

namespace Acme\StaffBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use JMS\SecurityExtraBundle\Annotation\Secure;

class DefaultController extends Controller {

  /**
   * @Route("/staff/{firm_id}", name="_get_staffs")
   * 
   */
  public function indexAction(\Symfony\Component\HttpFoundation\Request $request, $firm_id) {
    if ( $request->isXmlHttpRequest() ) {

      $page = $request->get('page');
      $rows = $request->get('rows');
      $sidx = $request->get('sidx');
      $sord = $request->get('sord');
      $js = array( );
      $start = $rows * $page - $rows;
      $repository = $this->getDoctrine()->getRepository('AcmeStaffBundle:Staff');

      $staffs = $repository->findBy(
              array( 'firm' => $firm_id ), array( $sidx => strtoupper($sord) ), $rows, $start);

      $count = count($staffs);
      if ( $count > 0 ) {
        $total_pages = ceil($count / $rows);
      }
      else {
        $total_pages = 0;
      }
      if ( $page > $total_pages )
        $page = $total_pages;
      $js['page'] = $page;
      $js['total'] = $total_pages;
      $js['records'] = $count;

      foreach ( $staffs as $key => $staff ) {
        $js['rows'][$key]['id'] = $staff->getId();
        $js['rows'][$key]['cell'] = array( $staff->getId(), $staff->getName(), $staff->getCategory()->getName(), '' );
      }
      $response = new \Symfony\Component\HttpFoundation\Response(json_encode($js), 200, array( 'Content-Type' => 'application/json' ));

      return $response;
    }
    return new \Symfony\Component\HttpFoundation\Response('', 404);
    //return array('name' => $name);
  }

  /**
   * @Secure(roles="ROLE_FIRM")
   * @Route("/del_staff", name="_del_staff")
   * 
   */
  public function deleteAction(\Symfony\Component\HttpFoundation\Request $request) {

    if ( $request->isXmlHttpRequest() ) {
      $id = $request->request->get('id');
      $id = html_entity_decode(trim($id));
      $ids = strstr($id, ',') ? explode(',', $id) : array( $id );
      $em = $this->getDoctrine()->getEntityManager();
      $repository = $em->getRepository('AcmeStaffBundle:Staff');
      foreach ( $ids as $v ) {
        $staff = $repository->findOneById($v);
        $em->remove($staff);
      }
      $em->flush();
    }
    return new \Symfony\Component\HttpFoundation\Response('', 200);
  }

  /**
   * @Secure(roles="ROLE_FIRM")
   * @Route("/add_staff/{firm_id}/{staff_id}", name="_add_staff", defaults={"staff_id" = null})
   * @Template()
   */
  public function addAction(\Symfony\Component\HttpFoundation\Request $request, $firm_id, $staff_id = null) {
    $em = $this->getDoctrine()->getEntityManager();
    if ($staff_id) {
      $staff = $em->getRepository('AcmeStaffBundle:Staff')->findOneById($staff_id);
    }
    else {
      $staff = new \Acme\StaffBundle\Entity\Staff();
    }
    $staff->setFirm($em->getRepository('AcmeFirmsBundle:Firms')->findOneById($firm_id));
    if ($request->request->has('category')) {
      $staff_category = new \Acme\StaffBundle\Entity\CategoryStaff();
      $staff_category->setName($request->request->get('category'));
      $em->persist($staff_category);
      $em->flush();
      $staff->setCategory($staff_category);
    }
    $form = $this->createForm(new \Acme\StaffBundle\Form\StaffForm(), $staff);
    if ( $request->getMethod() == 'POST' ) {
      $session = $request->getSession();
      $message = 'Данный не добавлены';
      $form->bindRequest($request);
      if ( $form->isValid() ) {
        $em->persist($staff);
        $em->flush();
        $message = 'Данный добавлены';
      }
      $session->setFlash('notice', $message);
      return $this->redirect($this->generateUrl('_firm_page'));
    }
    return array(
        'form' => $form->createView(),
        'firm_id' => $firm_id,
        'staff_id' => $staff_id
    );
  }
  
  /**
   *
   * @Route("/view_staff/{staff_id}", name="_view_staff")
   * @Template() 
   * 
   */
  public function viewAction(\Symfony\Component\HttpFoundation\Request $request, $staff_id) {
    $em = $this->getDoctrine()->getEntityManager();
    $staff = $em->getRepository('AcmeStaffBundle:Staff')->findOneById($staff_id);
    $comment = new \Acme\StaffBundle\Entity\Comment();
    $add_comment_form = $this->createForm(new \Acme\StaffBundle\Form\AddCommentForm(), $comment);
    return array(
          'staff' => $staff,
          'add_comment_form' => $add_comment_form->createView()
    );
  }

}
